package io.gitee.zhucan123.core.config.flyway;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

/**
 * @program: homo
 * @description: flyway配置类
 * @author: zhuCan
 * @date: 2019-06-20 18:54
 **/
@Slf4j
@Service
@EnableConfigurationProperties(FlywayProperties.class)
public class MigrationService implements ApplicationContextAware {

  @Autowired
  private DataSource dataSource;
  @Autowired
  private FlywayProperties properties;

  /**
   * 在所有bean容器装填完毕后,执行flyway.migrate来初始化脚本
   *
   * @param applicationContext
   * @throws BeansException
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) {
    // 先执行一次repair 删除失败的迁移
    repair();
    // 再执行未执行的脚本
    migrate();
  }

  /**
   * flyway:->执行迁移
   */
  public void migrate() {
    flyway().migrate();
    log.info("flyway migrate completed !");
  }

  /**
   * flyway:->执行修复
   */
  public void repair() {
    flyway().repair();
    log.info("flyway repair completed !");
  }

  /**
   * 加载flyway
   *
   * @return
   */
  private Flyway flyway() {
    // 创建flyway的配置对象
    FluentConfiguration configure = Flyway.configure();
    // 需要自己配置下数据源
    configure.dataSource(dataSource);
    // 装填属性
    FlywayProperties.configureProperties(configure, properties);

    // 通过配置类加载flyway对象
    return configure.load();
  }
}
